//
//  XMHomeController.m
//  XMWeibo
//
//  Created by chi on 14-8-19.
//  Copyright (c) 2014年 xiaoming. All rights reserved.
//

#import "XMHomeController.h"
#import "UIBarButtonItem+XM.h"
#import "XMTitleView.h"
#import "XMWeiboAccount.h"

#import "XMStatusCell.h"
#import "XMShowWeiboCountView.h"

#import "SoundTool.h"
#import "XMLoadStatusTool.h"
#import "XMLoadUserInfoTool.h"


#import "UIImageView+WebCache.h"
#import "MJRefresh.h"

#import "XMStatus.h"

#define kTitleViewHEdge (80.0)
#define kTitleViewVEdge (2.0)

 static NSString *resueIdentifier = @"statusCell";

@interface XMHomeController ()

/** 导航栏标题图 */
@property (nonatomic, weak) XMTitleView *tilteView;

/** 微博数据 */
@property (nonatomic, strong) NSMutableArray *stausList;


@end

@implementation XMHomeController



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    // 加载标题栏自定义控件
    [self setupNaviBar];
    
    // 加载刷新控件
    [self setupRefreshControl];
    
    // 加载缓存
    
    XMHttpGetStatusResult *result = [XMLoadStatusTool sqliteLoadStatusWithParams:[XMHttpGetStatusParams params]];
    if (result.statuses.count > 0) {
        
        NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:result.statuses.count];
        
        for (XMStatus *status in result.statuses) {
            XMStatusFrame *statusF = [[XMStatusFrame alloc]init];
            
            statusF.status = status;
            
            [arrayM addObject:statusF];
        }
        self.stausList = arrayM;
    }
    else {
        [self.tableView headerBeginRefreshing];
    }
    
    // 加载账号信息
    [self loadUserInfo];
    
    // 设置tableview属性

    self.tableView.backgroundColor = XMColor(219, 219, 219);
    self.tableView.contentInset = UIEdgeInsetsMake(0.0, 0.0, kStatusCellEdge, 0.0);
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    
}

/**
 *  从新浪加载微博帐号信息
 */
- (void)loadUserInfo
{
 
    XMHttpLoadUserInfoParams *params = [XMHttpLoadUserInfoParams params];
    params.uid = @([XMWeiboAccount account].uid);
    
    
    [XMLoadUserInfoTool httpLoadUserInfoWithParams:params success:^(XMHttpLoadUserInfoResult *result) {
        XMWeiboUser *user = result;
        [self.tilteView setTitle:user.screen_name forState:UIControlStateNormal];
        
        //归档
        [user saveWeiboUserToFile];
        
    } failure:^(NSError *error) {
        
        XMLog(@"%@请求失败，失败原因: %@", k_statuses_home_timeline, error);
    }];
    
}

/**
 *  提示新微博
 */
- (void)showRefreshWeiboCount:(NSUInteger)count
{
    if (count > 0) {
        [[SoundTool sharedSoundTool] playSoundByFileName:@"msgcome"];
    }
    
    XMShowWeiboCountView *msgView = [XMShowWeiboCountView buttonWithType:UIButtonTypeCustom];
    
    [self.navigationController.view insertSubview:msgView belowSubview:self.navigationController.navigationBar];
    
    [msgView setRefreshWeiboCount:count];
}

/**
 *  创建刷新控件
 */
- (void)setupRefreshControl
{
    
    //下拉刷新
    [self.tableView addHeaderWithTarget:self action:@selector(headerRefreshing)];
//    [self.tableView headerBeginRefreshing];
    
    //上拉刷新
    [self.tableView addFooterWithTarget:self action:@selector(footerRefreshing)];
    
}


/**
 *  开始下拉刷新
 */
- (void)headerBeginRefreshing
{
    [self.tableView headerBeginRefreshing];
}

/**
 *  下拉刷新
 */
- (void)headerRefreshing
{
    
    XMHttpGetStatusParams *params = [XMHttpGetStatusParams params];
    
    if (self.stausList.count > 0) {
        XMStatusFrame *statusF = self.stausList[0];
        params.since_id = @([statusF.status.idstr longLongValue]);
        
    }
    
    [XMLoadStatusTool loadStatusWithParams:params success:^(XMHttpGetStatusResult *result) {
        NSMutableArray *arrayM = [NSMutableArray array];

        
        for (XMStatus *status in result.statuses) {
            XMStatusFrame *statusF = [[XMStatusFrame alloc]init];
            
            statusF.status = status;
            
            [arrayM addObject:statusF];
        }
        
        if (self.stausList.count > 0) {
            [arrayM addObjectsFromArray:self.stausList];
        }
        
        self.stausList = arrayM;
        
        //刷新表格
        [self.tableView reloadData];
        
        //关闭刷新控件
        [self.tableView headerEndRefreshing];
        
        //提示新微博数量
        [self showRefreshWeiboCount:result.statuses.count];
        
        //清空badge
        self.tabBarItem.badgeValue = @"";
    } failure:^(NSError *error) {
        //请求失败
        [self.tableView headerEndRefreshing];
        
        XMLog(@"--------> headerRefreshing 失败 come here %@", error);
        
    }];
    
}

/**
 *  下拉刷新
 */
- (void)footerRefreshing
{
    
    
    XMHttpGetStatusParams *params = [XMHttpGetStatusParams params];
    
    if (self.stausList.count > 0) {
        XMStatusFrame *statusF = [self.stausList lastObject];
        params.max_id = @([statusF.status.idstr longLongValue] - 1);
        
    }
    
    [XMLoadStatusTool loadStatusWithParams:params success:^(XMHttpGetStatusResult *result) {
        NSMutableArray *arrayM = [NSMutableArray array];
        [arrayM addObjectsFromArray:self.stausList];
        
        for (XMStatus *status in result.statuses) {
            XMStatusFrame *statusF = [[XMStatusFrame alloc]init];
            
            statusF.status = status;
            
            [arrayM addObject:statusF];
        }
        
        
        self.stausList = arrayM;
        
        [self.tableView reloadData];
        
        [self.tableView footerEndRefreshing];
    } failure:^(NSError *error) {
        //请求失败
        [self.tableView headerEndRefreshing];
        
        XMLog(@"--------> footerRefreshing 失败 come here %@", error);
        
    }];
    
}



/**
 *  创建导航栏控件
 */
- (void)setupNaviBar
{
    //左边按钮
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithNormalImage:@"navigationbar_friendsearch" highlighted:@"navigationbar_friendsearch_highlighted" target:self action:@selector(searchFriend)];
    
    //右边按钮
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithNormalImage:@"navigationbar_pop" highlighted:@"navigationbar_pop_highlighted" target:self action:@selector(popView)];
    
    
    //中间的标题
    XMTitleView *titleView = [XMTitleView buttonWithType:UIButtonTypeCustom];
    self.tilteView = titleView;
    [titleView addTarget:self action:@selector(clickTitleView) forControlEvents:UIControlEventTouchUpInside];
    [titleView setImage:[UIImage adaptIOS7ImageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    
    //设置标题栏高度
    CGFloat naviH = self.navigationController.navigationBar.bounds.size.height;
    titleView.bounds = CGRectMake(0.0, 0.0, 0.0, naviH - kTitleViewVEdge * 2);
    
    //设置标题
    XMWeiboUser *weiboUser = [XMWeiboUser loadWeiboUserFromFile];
    if (weiboUser) {
        [titleView setTitle:weiboUser.screen_name forState:UIControlStateNormal];
    }
    else {
        [titleView setTitle:@"首页" forState:UIControlStateNormal];
    }
    
    
    self.navigationItem.titleView = titleView;
}

/**
 *  响应点击标题视图
 */
- (void)clickTitleView
{
    CGAffineTransform transform = CGAffineTransformIdentity;
    if (!self.tilteView.isArrowUP) {
        transform = CGAffineTransformMakeRotation(M_PI);
    }
    
    [UIView animateWithDuration:0.2f animations:^{
        self.tilteView.imageView.transform = transform;
    }];
    
    self.tilteView.isArrowUP = !self.tilteView.isArrowUP;
}



//弹出
- (void)popView
{
    XMLog(@"popView come here");
}

//搜索
- (void)searchFriend
{
    XMLog(@"searchfriend come here");
}



#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.stausList.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    XMStatusFrame *statusF = self.stausList[indexPath.row];
    XMStatusCell *cell = [XMStatusCell cellWithStatusFrame:statusF andTableView:tableView];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{
     XMStatusFrame *statusF = self.stausList[indexPath.row];
    
    return statusF.cellHeight;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
